#!/usr/bin/env node

// PWM控制调试脚本
const { spawn } = require('child_process');
const { resolve } = require('path');
const { promisify } = require('util');
const { exec } = require('child_process');
const execAsync = promisify(exec);

console.log("🔍 PWM控制调试脚本");

async function testGPIOCommands() {
  console.log("\n🔧 测试GPIO命令...");
  
  try {
    // 测试gpio命令是否可用
    const version = await execAsync('gpio -v');
    console.log("✅ gpio命令可用:", version.stdout.split('\n')[0]);
    
    // 测试引脚13设置为输出模式
    await execAsync('gpio -g mode 13 out');
    console.log("✅ 引脚13设置为输出模式");
    
    // 测试引脚12设置为输出模式
    await execAsync('gpio -g mode 12 out');
    console.log("✅ 引脚12设置为输出模式");
    
    return true;
  } catch (error) {
    console.error("❌ GPIO命令测试失败:", error.message);
    return false;
  }
}

function testPWMProcess() {
  console.log("\n🚀 测试PWM进程...");
  
  return new Promise((resolve) => {
    // 启动GPIO进程
    const gpioProcess = spawn(`sudo`, [
      process.execPath,
      resolve(__dirname, "./lib/gpio.js"),
    ]);
    
    let outputReceived = false;
    
    gpioProcess.stdout.on("data", (data) => {
      console.log("📤 GPIO进程输出:", data.toString());
      outputReceived = true;
    });
    
    gpioProcess.stderr.on("data", (data) => {
      console.log("❌ GPIO进程错误:", data.toString());
    });
    
    gpioProcess.on("error", (error) => {
      console.error("💥 GPIO进程启动错误:", error.message);
      resolve(false);
    });
    
    // 等待进程启动
    setTimeout(() => {
      if (!outputReceived) {
        console.log("📡 发送测试命令...");
        
        // 发送测试命令
        gpioProcess.stdin.write("pwm 13 0.5\n");
        console.log("  发送: pwm 13 0.5");
        
        // 等待响应
        setTimeout(() => {
          gpioProcess.stdin.write("pwm 13 0\n");
          console.log("  发送: pwm 13 0");
          
          // 关闭进程
          gpioProcess.stdin.write("exit\n");
          gpioProcess.kill();
          resolve(true);
        }, 2000);
      }
    }, 1000);
    
    // 超时处理
    setTimeout(() => {
      if (gpioProcess.pid) {
        gpioProcess.kill();
      }
      resolve(false);
    }, 10000);
  });
}

async function testHardwarePWM() {
  console.log("\n⚙️  测试硬件PWM...");
  
  try {
    // 直接测试硬件PWM
    const { default: hardwarePWM } = await import('./lib/hardwarePWM.js');
    
    console.log("  设置引脚13为0.5值...");
    await hardwarePWM.setPWM(13, 0.5);
    
    console.log("  等待2秒...");
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    console.log("  停止PWM...");
    await hardwarePWM.stopAllPWM();
    
    console.log("✅ 硬件PWM测试完成");
    return true;
  } catch (error) {
    console.error("❌ 硬件PWM测试失败:", error.message);
    return false;
  }
}

async function main() {
  console.log("🚀 开始PWM控制调试");
  
  // 测试GPIO命令
  const gpioSuccess = await testGPIOCommands();
  
  if (!gpioSuccess) {
    console.log("\n❌ GPIO命令测试失败，无法继续");
    return;
  }
  
  // 测试PWM进程
  const processSuccess = await testPWMProcess();
  
  // 测试硬件PWM
  const hardwareSuccess = await testHardwarePWM();
  
  console.log("\n📋 调试结果:");
  console.log(`  GPIO命令: ${gpioSuccess ? '✅' : '❌'}`);
  console.log(`  PWM进程: ${processSuccess ? '✅' : '❌'}`);
  console.log(`  硬件PWM: ${hardwareSuccess ? '✅' : '❌'}`);
  
  if (gpioSuccess && (processSuccess || hardwareSuccess)) {
    console.log("\n🎉 PWM控制应该正常工作！");
  } else {
    console.log("\n⚠️  PWM控制可能存在问题，请检查:");
    console.log("   1. WiringPi是否正确安装");
    console.log("   2. GPIO权限是否正确配置");
    console.log("   3. 硬件连接是否正确");
    console.log("   4. 电调是否需要校准");
  }
}

main();